package vn.fithou.hou_elearning.activity;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import vn.fithou.hou_elearning.R;
import vn.fithou.hou_elearning.parser.XMLParser;
import vn.fithou.hou_elearning.util.Config;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

public class SlideActivity extends Activity implements OnClickListener {
	// All static variables
	static final String URL = "http://10.0.2.2/hou-elearning/Service/HOULMSService.svc/";
	// XML node keys
	public static final String KEY_TRANGSLIDE = "TrangslideEntity"; // nút cha trang slide
	public static final String KEY_TRANGSLIDE_ID = "PK_iTrangslideID";
	public static final String KEY_TRANGSLIDE_NAME = "sTieude";
	public static final String KEY_SUKIENSLIDE = "SukienslideEntity"; //nút cha sự kiện slide
	public static final String KEY_SUKIENSLIDE_ID = "PK_iSukienslideID";
	public static final String KEY_SUKIENSLIDE_CONTENT = "sNoidung";
	
	ArrayList<HashMap<String, String>> arrlTrangslide = null; //Danh sách trang slide
    HashMap<String, ArrayList<HashMap<String, String>>> hmSukienslide = null; //Danh sách sự kiện
    
    int iCurrentPage = 0; //chỉ số của trang đang được hiển thị
    
	public WebView videoView = null;
	public WebView webView = null;
	public Button btnPrev = null;
	public Button btnNext = null;
	public TextView txtPageIndex = null;
	public TextView txtPageTitle = null;
	public String sVideo = "";
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.slide_layout);
        //Get PK_iSlideID from DanhsachSlideActivity
		int PK_iSlideID = 0;
		sVideo = "";
		Bundle extras = getIntent().getExtras();
		if(extras !=null) 
		{
			PK_iSlideID = extras.getInt(DanhsachSlideActivity.KEY_ID, 0);
			sVideo = extras.getString(DanhsachSlideActivity.KEY_VIDEO);
		}
		//Reset
		iCurrentPage = 0;
		//Init global variable
		arrlTrangslide = new  ArrayList<HashMap<String,String>>();
		hmSukienslide = new HashMap<String, ArrayList<HashMap<String,String>>>();
		//Get list data
		XMLParser parser = new XMLParser();
		//Lấy danh sách trang slide
		String xml = parser.getXmlFromUrl(URL + "TrangslideGetByFK_iSlideIDXML/" + PK_iSlideID, "POST"); // getting XML from URL
		Document doc = parser.getDomElement(xml); // getting DOM element
		NodeList nl = doc.getElementsByTagName(KEY_TRANGSLIDE);
		// looping through all song nodes <song>
		for (int i = 0; i < nl.getLength(); i++) {
			// creating new HashMap
			HashMap<String, String> map = new HashMap<String, String>();
			Element e = (Element) nl.item(i);
			// adding each child node to HashMap key => value
			map.put(KEY_TRANGSLIDE_ID, parser.getValue(e, KEY_TRANGSLIDE_ID));
			map.put(KEY_TRANGSLIDE_NAME, parser.getValue(e, KEY_TRANGSLIDE_NAME));

			// adding HashList to ArrayList
			arrlTrangslide.add(map);
		}
		
		//Init layout
		initLayout();
		//Display first page
		showCurentPage();
		//Init video
		initVideo();
//		Uri uri = Uri.parse("http://10.0.2.2" + sVideo);
//		videoView.setVideoURI(uri);
//		MediaController mc = new MediaController(this);
//		videoView.setMediaController(mc);
//		videoView.requestFocus();
//		videoView.start();
//		mc.show();
    }//End onCretate
    
    /*
	 * Khai báo các điều khiển trên layout
	 * */
    public void initLayout()
    {
    	videoView = (WebView)findViewById(R.id.videoView);
		webView = (WebView)findViewById(R.id.webView);
		btnNext = (Button)findViewById(R.id.btn_next);
		btnNext.setOnClickListener(this);
		btnPrev = (Button)findViewById(R.id.btn_prev);
		btnPrev.setOnClickListener(this);
		txtPageIndex = (TextView)findViewById(R.id.text_index);
		txtPageTitle = (TextView)findViewById(R.id.text_tieude);
    }
    
    /*
	 * Hiển thị danh sách sự kiện slide theo ID của trang slide hiện tại
	 * */
	public void showCurentPage()
	{
		int PK_iTrangslideID = Integer.parseInt(arrlTrangslide.get(iCurrentPage).get(KEY_TRANGSLIDE_ID));
		
		String sContent = "";
		XMLParser parser = new XMLParser();
		String xml = parser.getXmlFromUrl(URL + "SukienslideGetByFK_iTrangslideIDXML/" + PK_iTrangslideID, "POST"); // getting XML from URL
		Document doc = parser.getDomElement(xml); // getting DOM element
		NodeList nl = doc.getElementsByTagName(KEY_SUKIENSLIDE);
		
		StringBuilder html = new StringBuilder();
		html.append("<html>");
		html.append("<head>");
		html.append("<link rel=stylesheet href='css/style.css'>");
		html.append("</head>");
		html.append("<body>");
		for (int j = 0; j < nl.getLength(); ++j) {
			Element e = (Element) nl.item(j);
			sContent = parser.getValue(e, KEY_SUKIENSLIDE_CONTENT);
			sContent = sContent.replace("src=\"/hou-elearning", "src=\""+ Config.SERVER_HOST +"/hou-elearning");
			html.append(sContent);
			html.append("<br/>");
		}//End for j
		html.append("</body></html>");
		webView.loadDataWithBaseURL("file:///android_asset/", html.toString(), "text/html", "UTF-8", ""); //Hiển thị nội dung
		txtPageTitle.setText(arrlTrangslide.get(iCurrentPage).get(KEY_TRANGSLIDE_NAME)); //Hiển thị tiêu đề trang slide
		txtPageIndex.setText((iCurrentPage + 1) + "/" + arrlTrangslide.size()); //Hiển thị chỉ số trang
	}
    //xử lý nhấn nút
	@Override
	public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_prev:
        	//Kiểm tra vị trí có vượt ra ngoài danh sách
    		if(iCurrentPage <= 0)
    		{
    			iCurrentPage = arrlTrangslide.size()-1;
    		}
    		else
    		{
    			iCurrentPage--;
    		}
    		showCurentPage();
            break;
        case R.id.btn_next:
        	//Kiểm tra vị trí có vượt ra ngoài danh sách
    		if(iCurrentPage >= arrlTrangslide.size()-1)
    		{
    			iCurrentPage = 0;
    		}
    		else
    		{
    			iCurrentPage++;
    		}
    		showCurentPage();
           break;
        }   
    }
	
    //Hiển thị video
    public void initVideo()
    {
    	//sVideo = sVideo.replace("FLV", "mp4");
    	String htmlPre = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"></head><body style='margin:0; pading:0; background-color: black;'>";  
    	String htmlCode = 
    			" <embed style='width:100%; height:100%' src='http://www.platipus.nl/flvplayer/download/1.0/FLVPlayer.swf?fullscreen=true&video=@VIDEO@' " +
    			"  autoplay='false' " +
    			"  quality='high' bgcolor='#000000' " +
    			"  name='VideoPlayer' align='middle'" + // width='640' height='480' 
    			"  allowScriptAccess='*' allowFullScreen='true'" +
    			"  type='application/x-shockwave-flash' " +
    			"  pluginspage='http://www.macromedia.com/go/getflashplayer' />" +
    			"";
    	String htmlPost = "</body></html>";
    	
    	videoView.getSettings().setJavaScriptEnabled(true);
    	videoView.getSettings().setAllowFileAccess(true);
    	videoView.getSettings().setPluginsEnabled(true);
    	videoView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
			
		htmlCode = htmlCode.replaceAll("@VIDEO@", "http://10.0.2.2" + sVideo);
		videoView.loadDataWithBaseURL("fake://fake/fake", htmlPre + htmlCode + htmlPost, "text/html", "UTF-8", null);  
    }
    
    @Override
    protected void onPause(){
        super.onPause();
        
        callHiddenWebViewMethod("onPause");

        videoView.pauseTimers();
        if(isFinishing()){
        	videoView.loadUrl("about:blank");
            setContentView(new FrameLayout(this));
        }
    }

    @Override
    protected void onResume(){
        super.onResume();

        callHiddenWebViewMethod("onResume");

        videoView.resumeTimers();
    }
    
    private void callHiddenWebViewMethod(String name){
        if( videoView != null ){
            try {
                Method method = WebView.class.getMethod(name);
                method.invoke(videoView);
            } catch (NoSuchMethodException e) {
                Log.i("Load video error: ", "No such method: " + name + e);
            } catch (IllegalAccessException e) {
                Log.i("Load video error: ", "Illegal Access: " + name + e);
            } catch (InvocationTargetException e) {
                Log.i("Load video error: ", "Invocation Target Exception: " + name + e);
            }
        }
    }
}